package com.lzy.system.fileManage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.extra.ssh.Sftp;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.exception.BusException;
import com.lzy.system.fileManage.UploadFileProperties;
import com.lzy.system.fileManage.entity.SysFile;
import com.lzy.system.fileManage.mapper.SysFileMapper;
import com.lzy.system.fileManage.service.ISysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

/**
 * <p>
 * 附件管理 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2023-12-28
 */
@Service
@Slf4j
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements ISysFileService {

    @Autowired
    private UploadFileProperties uploadFileProperties;

    /**
     * 接收上传的文件并且存储到数据中，如果开启了ftp则自动上传到ftp服务器
     * <p>
     * 文本存储路径 = 本地配置路径+年月日+系统uuid+.文件后缀
     * 并且存储到数据中
     *
     * @param uid
     * @param file
     * @return
     * @throws BusException
     */
    @Override
    public SysFile saveFile(Long uid, MultipartFile file) throws BusException {
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String sysFileName = IdUtil.fastSimpleUUID() + "." + suffix;
        //系统动态存储地址
        String sysPath = "/" + DateUtil.format(DateUtil.date(), "yyyy-MM-dd") + "/";
        Path path = Paths.get(uploadFileProperties.getPath() + sysPath + sysFileName);
        log.debug(StrUtil.format("保存路径：{}", path.toString()));
        try {
            File dir = path.getParent().toFile();
            if (!dir.isDirectory()) {
                dir.mkdirs();
            }
            file.transferTo(path);//转存文件
            if (uploadFileProperties.isFtp()) {
                if (uploadFileProperties.getFtpType().equals("ftp")) {
                    //匿名登录（无需帐号密码的FTP服务器）
                    Ftp ftp = new Ftp(uploadFileProperties.getFtpIp(), uploadFileProperties.getFtpPort(), uploadFileProperties.getFtpUser(), uploadFileProperties.getFtpPwd());
                    String ftp_path = uploadFileProperties.getFtpPath() + sysPath;
                    if (ftp.isDir(ftp_path)) {
                        ftp.mkDirs(ftp_path);
                    }
                    ftp.upload(ftp_path, sysFileName, path.toFile());
                    ftp.close();
                } else if (uploadFileProperties.getFtpType().equals("sftp")) {
                    Sftp sftp = JschUtil.createSftp(uploadFileProperties.getFtpIp(), uploadFileProperties.getFtpPort(), uploadFileProperties.getFtpUser(), uploadFileProperties.getFtpPwd());
                    String ftp_path = uploadFileProperties.getFtpPath() + sysPath;
                    if (!sftp.isDir(ftp_path)) {
                        sftp.mkDirs(ftp_path);
                    }
                    sftp.upload(ftp_path + sysFileName, path.toFile());
                    sftp.close();
                    log.debug(StrUtil.format("上传sftp成功：{}", ftp_path + sysFileName));
                }
            }
            SysFile sysFile = new SysFile();
            sysFile.setFile_name(file.getOriginalFilename());
            sysFile.setSys_file_name(sysFileName);
            sysFile.setFile_type(suffix);
            sysFile.setFile_path(sysPath);
            sysFile.setCreate_user(uid);
            sysFile.setCreatedate(new Date());
            sysFile.setFile_size(file.getSize());
            sysFile.setUpload_source("user-img-upload");
            save(sysFile);

            return sysFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getFile(String id) throws BusException {
        String path = null;
        try {
            SysFile sysFile = getById(id);
            if (sysFile == null) {
                throw new BusException("文件不存在");
            }
            path = uploadFileProperties.getPath() + sysFile.getFile_path() + sysFile.getSys_file_name();
            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                //如果本地文件不存在查看是否在sftp上
                if (uploadFileProperties.isFtp()) {
                    if (uploadFileProperties.getFtpType().equals("ftp")) {
                        Ftp ftp = new Ftp(uploadFileProperties.getFtpIp(), uploadFileProperties.getFtpPort(), uploadFileProperties.getFtpUser(), uploadFileProperties.getFtpPwd());
                        String ftp_path = uploadFileProperties.getFtpPath() + sysFile.getFile_path() + sysFile.getSys_file_name();
                        ftp.download(ftp_path , new File(uploadFileProperties.getPath() + sysFile.getFile_path()));
                        ftp.close();
                    } else if (uploadFileProperties.getFtpType().equals("sftp")) {
                        Sftp ftp = new Sftp(uploadFileProperties.getFtpIp(), uploadFileProperties.getFtpPort(), uploadFileProperties.getFtpUser(), uploadFileProperties.getFtpPwd());
                        String ftp_path = uploadFileProperties.getFtpPath() + sysFile.getFile_path() + sysFile.getSys_file_name();
                        ftp.download(ftp_path , new File(uploadFileProperties.getPath() + sysFile.getFile_path()));
                        ftp.close();
                    }
                }
                file = new File(path);
                if (!file.exists()) {
                    throw new RuntimeException("文件不存在");
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return path;
    }
}